﻿if __UNIT_TEST__ then

module(...,package.seeall)
--Define clone here in case we need it
local truetype = truetype or type
clone = clone or function(t)
  local u = setmetatable ({}, getmetatable (t))
  local k,v
  for k, v in pairs (t) do
    if truetype(v)=="table" then
      if v ~= t then -->avoid cycles
        u[k] = clone(v)-->recursively clone subtables
      end
    else
      u[k] = v
    end
  end
  return u
end

unittest_mt = {
  equal = function(a,b)
    return a == b
  end,
  notequal = function(a,b)
    return a ~= b
  end,
  exception = function(a,b)
    local ok, err = pcall(a)
    if not ok then
      return err == b
    end
  end,
  __index = function(t,k)
    return unittest_mt[k] or _G[k]
  end
}


start = function()
  local ut = clone(getfenv(2)) --> create a copy of the local enviroment so we can mess with it
  ut.__oldenv = getfenv(2) --> keep a reference to the old environment so we can restore later
  -- Include testing facilities to the environment
  setmetatable (ut,unittest_mt)
  setfenv(2, ut)
end

stop = function()
  setfenv(2, getfenv(2).__oldenv) -->Return the environment to what it should be
end

--[[--Usage sample
if __UNIT_TEST__ then
  unittest.start()
  
    print(equal(1,1))
    print(notequal(1,2))
    
  unittest.stop()
end
--]]--

end

--Add a timeout function, or a perfomance time check to see if an algorithm takes too long
function lesstime(fun,seconds, cycles)
  local start = clock
  local cycles = cycles or 1
  while cycles > 0 do
     fun()
     cycles = cycles - 1
  end
  if (clock-start<s) then
     return true
  else
     return false
  end        
end

function moretime(fun,seconds, cycles)
  local start = clock
  local cycles = cycles or 1
  while cycles > 0 do
     fun()
     cycles = cycles - 1
  end
  if (clock-start<s) then
     return false
  else
     return true
  end        
end
